from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import logging
from django.core import serializers
from django.db.models import Q, F
import json, math, time, re

logger = logging.getLogger('log')

from ..serverEvCfg import httpResponseSignal
from ..models import  ptResponseContentReport
from ..dataBaseSQL.mysqlDB import getmoreSql
from ..serverEvCfg.sqlXmlOperate import get_sql
from ..serverEvCfg import asynTaskExecution
from ..tasks import ExecuteTestPlanAsynchronously

sqlXmlPath = "testPlan.xml"


@csrf_exempt
@api_view(["POST"])
def getDetailCasereQuest(request):
    '''
    获取全部多級聯動筛选条件（项目->组->请求）
    '''
    try:
        # 解析xml执行sql
        sql = get_sql("Case", "Query", "allProject", sqlname=sqlXmlPath, fileName="wzyTestPlanService")
        projects = getmoreSql(sql)
        sql1 = get_sql("Case", "Query", "allGroup", sqlname=sqlXmlPath, fileName="wzyTestPlanService")
        groups = getmoreSql(sql1)
        sql2 = get_sql("Case", "Query", "allRequest", sqlname=sqlXmlPath, fileName="wzyTestPlanService")
        requests = getmoreSql(sql2)
        for i in range(len(projects)):
            group_list = []
            for j in range(len(groups)):
                request_list=[]
                if str(groups[j]["group_pj_id"]) == str(projects[i]["pj_id"]):# 根据ID 关联项目和组的关系
                    group_list.append(groups[j]) # 每个项目中有多少组
                    projects[i]["groupList"] = group_list # 把项目和分组的关系，添加到

                for k in range(len(requests)):
                    if str(requests[k]["request_group_id"]) == str(groups[j]["group_id"]):
                        request_list.append(requests[k])
                        groups[j]["rqlist"] = request_list
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = projects
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)


@csrf_exempt
@api_view(["POST"])
def getDetailTestcase(request):
    '''
    获取符合条件测试用例
    '''
    data = json.loads(request.body)
    try:
        count = get_sql("Case", "Query", "queryPlanCaseCount", sqlname=sqlXmlPath, fileName="wzyTestPlanService")
        test = get_sql("Case", "Query", "queryPlanCase", sqlname=sqlXmlPath, fileName="wzyTestPlanService")
        sql = ""
        if data["pro_id"] != "":
            sqlpj = " AND pj.pj_id = %s" % (data["pro_id"])
            sql = sql + sqlpj
            if data["groupid"] != "":
                sqlgr = " AND gr.group_id = %s" % (data["groupid"])
                sql = sql + sqlgr
                if data["requestid"] != "":
                    sqlrq = " AND rq.request_id = %s" % (data["requestid"])
                    sql = sql + sqlrq

        if data["caseName"] != "":
            sqlcaseName = ' AND rc.case_name LIKE "%s"' % ("%" + str(data["caseName"]) + "%")
            sql = sql + sqlcaseName
        sql1 = sql
        sql = sql + " ORDER BY rc.creat_time DESC LIMIT %s,%s" % (
            (int(data["pageNum"]) - 1) * int(data["pageSize"]), data["pageSize"])

        countdata = getmoreSql(test + sql)  # 查询结果数据
        count = getmoreSql(count + sql1)  # 总数
        countNum = math.ceil(count[0]["count"] / data["pageSize"])  # 总页数
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = countdata
        response["caseCount"] = count[0]["count"]  # 总数
        response["countNum"] = countNum  # 总页数
        response["pageNum"] = data["pageNum"]  # 当前页数
        response["pageSize"] = data["pageSize"]  # 一页多少数
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
    return JsonResponse(response)

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addTestPlan(request):
    """
    添加,修改测试计划
    """
    data = json.loads(request.body)
    try:
        planName = ptResponseContentReport.objects.filter(plan_name=data["name"]).values()

        if list(planName) == []:# 查询一下 如果没有则新增测试计划
            testplan = ptResponseContentReport(plan_name=data["name"], store_test_case=data["testCaseList"],
                                                    timing_open_close=data["timing_open_close"],
                                                    timing_task=data["timing_task"],
                                                    case_total=len(data["testCaseList"]),
                                                    remark=data["remark"], execution_state="1")
            if data["timing_open_close"] == True: # 新增测试计划中携带定时任务信息
                if data["timing_task"] == "":
                    response = httpResponseSignal.httpResponseSignal().getFail()
                    response["msg"] = "输入定时任务时间不能为空"
                else:
                    data["timing_task"] = re.split(" ", data["timing_task"])
                    if len(data["timing_task"]) != 5:
                        logger.info('不正确定时任务格式：%s' % data["timing_task"])
                        response = httpResponseSignal.httpResponseSignal().getFail()
                        response["msg"] = "定时任务时间输入不正确，请重新输入"
                    else:
                        testplan.timing_task = data["timing_task"]
                        testplan.save()
                        response = httpResponseSignal.httpResponseSignal().getSuccess()
                        # 开始定时任务
                        asynTaskExecution.ptTask().start(plan_id=testplan.plan_id)
            else:
                testplan.save() # 新增计划
                response = httpResponseSignal.httpResponseSignal().getSuccess()
        else:
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"] = "测试计划名称是唯一的，请重新变更‘计划名称’"
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def deleteTestPlan(request):
    """
    :param request: 删除测试计划
    :return:
    """
    data = json.loads(request.body)
    print(data)
    try:
        mrcr = ptResponseContentReport.objects.filter(plan_id=data["id"]).get()
        print(mrcr.timing_open_close)
        if mrcr.timing_open_close == 'True':
            asynTaskExecution.ptTask().delete(plan_id=data["id"]) # 删除定时任务
        mrcr.delete() # 删除
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def queryTestPlan(request):
    """
    :param request: 查询测试计划
    :return:
    """
    data = json.loads(request.body)
    print(data)
    try:
        if data["creat_time"] == None:
            data["creat_time"] = [1572537600000, 1956412800000]
        for i in range(0, 2):
            creat_time = time.localtime(data["creat_time"][i] / 1000)
            data["creat_time"][i] = time.strftime("%Y-%m-%d %H:%M:%S", creat_time)

        pageSize = data["pageSize"]
        pageNum = data["pageNum"]
        reportList = ptResponseContentReport.objects.filter(
            Q(plan_name__icontains=data["plan_name"]) & Q(timing_open_close__icontains=data["timing_open_close"]) & Q(
                updata_time__range=(data["creat_time"]))).order_by("-creat_time")  # 创建时间改修改时间
        count = reportList.count()  # 总数
        datalist = json.loads(serializers.serialize("json", reportList))[
                   pageSize * pageNum - pageSize:pageSize * pageNum]

        for i in range(len(datalist)):
            creatTime = datalist[i]["fields"]["creat_time"]
            updata_time = datalist[i]["fields"]["updata_time"]
            datalist[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0] + " " + re.split('[TZ.]', creatTime)[
                1]
            datalist[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + \
                                                   re.split('[TZ.]', updata_time)[1]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = datalist
        response["pageNum"] = pageNum
        response["pageSize"] = pageSize
        response["gourpCount"] = count
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)

from django.db.transaction import on_commit
@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def executetTestPlan(request):
    """
    执行测试计划
    """
    data = json.loads(request.body)
    try:
        asynTaskExecution.ptTask().waitForPlan(id=data["id"]) # 加入执行计划中
        print('run star********')
        ExecuteTestPlanAsynchronously.delay(data["id"]) # 正式yibu执行计划，异步任务
        # ExecuteTestPlanAsynchronously(48) # 正式同步执行计划，手动跑任务
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        asynTaskExecution.ptTask().errorTestPlan(id=data["id"])
        logger.error(e)
